package dao

import (
	"fmt"
	"go_src/common"
	"go_src/common/exception"
	"reflect"
	"strings"
)

func getNotNullFieldValueMap(obj interface{}, excludeKeys []string) map[string]string {

	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	fieldValueMap := make(map[string]string)
	for i := 0; i < t.NumField(); i++ {
		key := t.Field(i)
		col := key.Tag.Get("db")
		if len(col) == 0 {
			continue
		}
		value := v.Field(i).Interface()
		if value != nil && !common.IsContain(col, excludeKeys) {
			switch v.Field(i).Kind() {
			case reflect.String:
				fieldValueMap[col] = "'" + value.(string) + "'"
			case reflect.Map:
				fieldValueMap[col] = "'" + common.ToJson(value) + "'"
			case reflect.Interface:
				fieldValueMap[col] = "'" + common.ToJson(value) + "'"
			default:
				fieldValueMap[col] = fmt.Sprintf("%v", value)
			}
		}
	}

	return fieldValueMap
}

func getInsertSql(obj interface{}) common.Result {

	fieldValueMap := getNotNullFieldValueMap(obj, []string{})
	if len(fieldValueMap) == 0 {
		return common.Result{Success: false, Error: exception.BusinessError{Code: exception.ParamExceptionCode, Message: "参数错误"}}
	}

	var vals []string
	var keys []string
	for k, v := range fieldValueMap {
		keys = append(keys, k)
		vals = append(vals, v)
	}
	insertSql := fmt.Sprintf("insert into %s (%s)values (%s)", common.GetFieldValueOfObj(obj, "TableName"),
		strings.Join(keys, ","), strings.Join(vals, ","))
	return common.Result{Success: true, Data: insertSql}
}

func executeChangeSql(sql string) common.Result {
	ret, err := Db.Exec(sql)
	if err != nil {
		fmt.Println(err)
		return common.Result{Success: false, Error: exception.BusinessError{Code: exception.DbOperatorExceptionCode,
			Message: "数据库错误", OriginalError: err}}
	}
	n, err := ret.RowsAffected() // 操作影响的行数
	if err != nil {
		return common.Result{Success: false, Error: exception.BusinessError{Code: exception.DbOperatorExceptionCode,
			Message: "数据库错误", OriginalError: err}}
	}
	if n > 0 {
		return common.Result{Success: true}
	} else {
		return common.Result{Success: false}
	}
}
